<?php
/**
 * QueryController.class.php
 * 
 * @author lsl8966
 * @copyright www.cnblog.com/lsl8966
 * @package Controller
 * @version $Id: GoodsController.class.php 1.0 2014-12-23 22:18:13Z $
 */
class PublicController extends Service{
    protected $api_key = 'hatch';
    protected $api_sign = '2423sdf34sdfsd32435sd';
    protected   $user_id;
    protected   $auth_verify = false;
    public   $default_db = 'db_sys';
    protected $default_table_prefix;

    protected $model = null;

    protected function parseParams(){
        $this->api_key = $this->jsonObj->api_key;
        $this->api_sign = $this->jsonObj->api_sign;
        $this->user_id = $this->jsonObj->user_id;
        self::$_extensionArray['m'] = $this->jsonObj->m?$this->jsonObj->m:'t_sys_app';
    }

    protected function _getDbNameByTableName($table_name){
        $app_plugin_id = session::get('app_plugin_id');
        $arr = explode('_',$table_name);
        //系统底层库
        if($arr[1] == 'sys'){
            $db_name = 'db_sys';
        }else{
            $db_name = "db_sys_26_71";
        }
        return $db_name;
    }

    function __destruct(){
    }

    protected function getTableName($name){
		$this->default_table_prefix = 't_26_';
        if(!strstr($name,$this->default_table_prefix)){
             $this->default_table_prefix.$name;
            return $this->default_table_prefix.$name;
        }else{
            return $name;
        }
    }

    /**
     * 前函数
     */
    protected function init(){
         parent::init();
        $this->parseParams();
        $amode = Controller::createMode('db_sys','t_sys_app');
        $this->default_db = 'db_sys_26_71';
		
        $this->_getDbNameByTableName(self::$_extensionArray['m']);
         if( $this->auth_verify  ){
             $this->authVerify();
         }
         $app_model = $this->model(self::$_extensionArray['m']);
         $this->model = Controller::createMode($this->default_db,self::$_extensionArray['m']);
         if($this->default_db){
             $this->model->setConfig($this->getConfig($this->default_db));
         }
         if(is_null($app_model)){
             $table_name = self::$_extensionArray['m'];
         } else {
             if($this->default_db){
                 $app_model->setConfig($this->getConfig($this->default_db));
             }
             $table_name = $app_model->tableName();
         }
         $this->model->setTableName($table_name);
         self::$_extensionArray['keys'] = array();
         foreach(self::$_extensionArray['table_info'] as $field=>$row ){
             if(strpos($row['comment'],'|')){
                 $table_info[$field]['comment'] = substr($row['comment'],0,strpos($row['comment'],'|'));
             }
             if($row['pk']){
                 self::$_extensionArray['keys'][$field] = '';
             }
         }
         self::$_extensionArray['o'] = array(
         );
     }

    /**
     * 登录
     */
    public function loginAction(){
        $map['mobile'] = strval($this->jsonObj->mobile);
        $map['password'] = strval($this->jsonObj->password);
        if($map['mobile'] == '' || $map['password'] == ''){
            $this->ajax(40000,null,array());
        }
        try{
            $list = $this->model->from(self::$_extensionArray['m'])->where($map)->limit(1)->select();
        }catch (Exception $e){
        }
        if( $list[0]['user_id'] ){
            $this->ajax(200,null,array('user_id'=>$list[0]['user_id'],'user_type'=>$list[0]['type'],'auth_key'=>uniqid()));
        } else {
            unset($map['password']);
            $list = $this->model->from(self::$_extensionArray['m'])->where($map)->limit(1)->select();
            if( !$list[0]['user_id'] ){
                $this->ajax(602,null,array());
            } else {
                $this->ajax(601,null,array());
            }
        }
    }

    /**
     * select
     */
    public function selectAction(){
        $page_size = $this->jsonObj->page_size?$this->jsonObj->page_size:0;
        if($this->jsonObj->fields){
            $excs = explode(',',$this->jsonObj->fields);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(!in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        }elseif($this->jsonObj->except){
            $excs = explode(',',$this->jsonObj->except);
            foreach(self::$_extensionArray['table_info'] as $key=>$field){
                if(in_array($key,$excs) ){
                    unset(self::$_extensionArray['table_info'][$key]);
                }
            }
        } else {
            //TODO 所有字段都展示
        }
        $fileds = implode(',',array_keys(self::$_extensionArray['table_info']));
        $where = $this->parseWhere();
        $order = $this->parseOrder();
        if(count($order)>0){
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->order($order)->select();
        }else {
            $list = $this->model->where($where)->field($fileds)->limit($page_size+1)->select();
        }
        if(count($list) == $page_size+1){
            self::$_extensionArray['o']['finish'] = 1;
            self::$_extensionArray['o']['list'] = array_slice($list,0,$page_size);
        } else {
            self::$_extensionArray['o']['finish'] = 0;
            self::$_extensionArray['o']['list'] = is_array($list)?$list:array();
        }
        self::$_extensionArray['o']['list'] = is_array(self::$_extensionArray['o']['list'])?self::$_extensionArray['o']['list']:array();
        $this->ajax(200,null,self::$_extensionArray['o']);
    }

    /**
     * delete
     */
    public function deleteAction(){
        if(!$this->jsonObj->map){
            $map = self::$_extensionArray['keys'];
            foreach($map as $key=>$row ){
                $map[$key] = $this->jsonObj->$key;
            }
        }else{
            $map = $this->parseWhere();
        }
        if($map){
            if( $this->model->delete($map)){
                $this->ajax(200,null,$map);
            } else {
                $this->ajax(417,null,$map);
            }
        }
    }

    /**
     * detail
     */
    public function detailAction(){
        $map = self::$_extensionArray['keys'];
        foreach($map as $key=>$row ){
            $map[$key] = $this->jsonObj->$key;
        }
        $data = array();
        if(is_array($map)){
            $data = $this->model->getOne($map);
            $data = $this->typeValueToString($data);
        }
        $this->ajax(200,null,$data);
    }

    /**
     * insert
     */
    public function insertAction(){
        if($this->jsonObj){
            $data = array();
            $params = (array)$this->jsonObj;
            $data['last_insert_id'] = $this->model->insert($params);
            if( $data['last_insert_id'] ){
                $this->ajax(200,null,$data);
            }else{
                $data['last_insert_id'] = '';
                $this->ajax(417,null,$data);
            }
        }
    }

    /**
     * update
     */
    public function updateAction(){
        if(!$this->jsonObj->map){
            $map = self::$_extensionArray['keys'];
            foreach($map as $key=>$row ){
                $map[$key] = $this->jsonObj->$key;
            }
        } else{
            $map = $this->parseWhere();
        }
        if($map){
            $params = (array)$this->jsonObj;
            if( $this->model->update($params,$map) ){
                $this->ajax(200,null,$map);
            }else{
                $this->ajax(417,null,$map);
            }
        }  else {
            $this->ajax(417,null,$map);
        }
    }

    /**
     * update
     */
    public function replaceAction(){
        $map = self::$_extensionArray['keys'];
        foreach($map as $key=>$row ){
            $map[$key] = $this->jsonObj->$key;
        }
        if($_POST || $_GET){
            $params = (array)$this->jsonObj;

            if($this->jsonObj->m == 't_29_ziliaorenzhengbiao'){

                $map['type'] = $this->jsonObj->type ? $this->jsonObj->type : 1;
            }
            $count = $this->model->count($this->model->getTableName(),"1",$map);
            if($this->jsonObj->m == 't_29_ziliaorenzhengbiao' || $this->jsonObj->m == 't_29_service_provider' ||
                $this->jsonObj->m == 't_29_service_driver' || $this->jsonObj->m == 't_29_service_boss'){
                //添加默认成“审核中”状态
                $params['state'] = 3;
            }
            if($count == 0){

                if( $this->model->addData($params) ){
                    $this->ajax(200,null,$map);
                }else{
                    $this->ajax(417,null,$map);
                }
            }else {
                if( $this->model->updateData($params,$map, false) ){
                    $this->ajax(200,null,$map);
                }else{
                    $this->ajax(417,null,$map);
                }
            }
        }  else {
            $this->ajax(417,null,$map);
        }
    }

    /**
     * count
     */
    public function countAction(){
        $where = $this->parseWhere();
        $count = $this->model->where($where)->count();
        $data = array();
        $data['count'] = $count?$count:0;
        if( $data['count'] ){
            $this->ajax(200,null,$data);
        } else if( $data['count'] === 0){
            $this->ajax(200,null,$data);
        }else{
            $data['count'] = 0;
            $this->ajax(417,null,$data);
        }
    }

    /**
     * 查询app应用信息
     */
    public function appinfoAction(){
        $app_info = $this->getAppInfo();
        if($app_info){
            $this->ajax(200,'OK',$app_info);
        } else {
            $this->ajax(417,null,array());
        }
    }

    public function getShopAppListAction(){
        $model = Controller::createMode('db_sys','t_sys_app');
        $arr = array(28,29,30,55,71,72,73,74);
        $data['list'] = $model->field("title,app_key,app_kind,description,app_icon")->where("app_id in (".implode(',',$arr).")")->select();
        $this->ajax(200,'OK',$data);
    }

    /**
     * 查询指定模型字段信息
     */
    public function getModelInfoAction(){
        $model_sys = Controller::createMode('db_sys','t_sys_model');
        $reuslt = array();
        $reuslt['configs'] = array();
        if(strpos($this->jsonObj->api_key,'.')){
            $this->jsonObj->api_key = strstr($this->jsonObj->api_key,".",true);
        }
        $configs = $model_sys->getOne(array('app_key'=>$this->jsonObj->api_key,'model_name'=>$this->jsonObj->m));
        if(!$configs){
            $configs = $model_sys->from(array('t_sys_model_ext'))->where(array('app_key'=>$this->jsonObj->api_key,'model_name'=>$this->jsonObj->m))->select(false);
        }
        unset($configs['create_sql']);
        if(!$configs) $configs = array();
        $ext = $model_sys->from(array('t_sys_model_profile'))->where(array('app_key'=>$this->jsonObj->api_key,'model_name'=>$this->jsonObj->m))->select(false);
        if(!$ext) $ext = array();
        $reuslt['configs'] = array_merge($configs,$ext);
        $reuslt['fields'] = is_array(self::$_extensionArray['table_info'])?self::$_extensionArray['table_info']:array();
        $this->ajax(200,'ok',$reuslt);
    }

    /**
     * 验证api_key的有效性
     * @param $api_key
     * @param $api_secret
     * @return bool
     */
    private function getAppInfo(){
        $map['app_key'] = "'".$this->api_key."'";
        $model = new Model();
        $model->setConfig($this->getConfig(self::$_extensionArray['g']));
        $data  = $model->from('t_sys_app')->where($map)->limit(1)->select();
        if($data[0]['app_id'] > 0 ){
            return $data[0];
        } else {
            return array();
        }
    }

    private   function authVerify (){
        if( strtolower(pdk::getActionName()) != 'login' && strtolower(pdk::getActionName()) != 'docs'){
            $model = new Model();
            $map['user_id'] = $this->user_id;
            $model->setConfig($this->getConfig(self::$_extensionArray['g']));
            $user_info  = $model->from('t_19_yonghuliebiao')->where($map)->limit(1)->select();
            if( !$user_info[0]['user_id'] ){
                $this->ajax(602,null,array());
            }
            $appinfo = $this->getAppInfo();
            if( !$appinfo['app_id'] ){
                $this->ajax(401);
            }
            $sign = md5($user_info['user_id'].$user_info['password'].$appinfo['api_key'].$appinfo['api_sercet']);
            if($sign == $this->api_sign ){
                return true;
            } else {
                $this->ajax(401);
            }
        }
        return true;
    }

    /**
     * 上传附件至七牛云存储
     */
    public function uploadAction(){
        $model = $this->module('qiniu');
        $isTest = true;
        $model->setConfig();
        if($isTest){
            $filename = 'avatar/'.time().".png";
            if(file_exists(MODULE_DIR.'qiniu/examples/php-logo.png')){
                $res = $model->upload(MODULE_DIR.'qiniu/examples/php-logo.png',$filename);
                echo $model->config['domian'].$filename;
            }else{
                $this->ajax(401,'file not found');
            }
        }else{
            $filename = 'avatar/'.time().".png";
            if(file_exists(MODULE_DIR.'qiniu/examples/php-logo.png')){
                $res = $model->upload(MODULE_DIR.'qiniu/examples/php-logo.png',$filename);
                echo $model->config['domian'].$filename;
            }else{
                $this->ajax(401,'file not found');
            }
        }
    }
}
